#!/bin/bash
################################################################################
# FurryOS Master Build System v4.0
# "I designed the OS, and AI wrote the code."
#
# FEATURES:
# - Mode Switcher on Desktop
# - Startup Sound (MP3)
# - Live Border
# - Bloat-free Base
################################################################################

set -e
set -o pipefail
set -u

# --- CONFIGURATION ---
readonly OS_NAME="Furryos"
readonly VERSION="8.1.0"
readonly DEBIAN_RELEASE="trixie" # Testing/Sid
readonly ARCH="amd64"
readonly DATE=$(date +%Y%m%d-%H%M)
readonly BUILD_LOG="build-${DATE}.log"

readonly WORK_DIR="$(pwd)"
readonly PARENT_DIR="$(dirname "$WORK_DIR")"
readonly BUILD_OUTPUT_DIR="$PARENT_DIR/FurryOS-Builds"

# --- COLORS ---
readonly C_GREEN='\033[0;32m'
readonly C_BLUE='\033[0;34m'
readonly C_RED='\033[0;31m'
readonly C_NC='\033[0m'

# --- LOGGING FUNCTIONS ---
log_info() { echo -e "${C_BLUE}[INFO]${C_NC} ${*}" | tee -a "$BUILD_LOG"; }
log_success() { echo -e "${C_GREEN}[SUCCESS]${C_NC} ${*}" | tee -a "$BUILD_LOG"; }
log_error() { echo -e "${C_RED}[ERROR]${C_NC} ${*}" | tee -a "$BUILD_LOG"; }

# --- CHECKS ---
check_root() {
    if [ "$EUID" -ne 0 ]; then
        log_error "Must run as root: sudo ./build4.sh"
        exit 1
    fi
}

check_dependencies() {
    local missing=()
    for cmd in lb rsync debootstrap xorriso mksquashfs; do
        if ! command -v "$cmd" &>/dev/null; then missing+=("$cmd"); fi
    done
    if [ ${#missing[@]} -gt 0 ]; then
        log_error "Missing dependencies: ${missing[*]}"
        log_info "Run: sudo apt install live-build rsync debootstrap xorriso squashfs-tools"
        exit 1
    fi
}

# --- CLEANUP ---
cleanup_environment() {
    log_info "Cleaning previous build environment..."

    # Unmount potentially stuck directories
    umount -lf chroot/dev/pts 2>/dev/null || true
    umount -lf chroot/dev 2>/dev/null || true
    umount -lf chroot/proc 2>/dev/null || true
    umount -lf chroot/sys 2>/dev/null || true

    lb clean --purge 2>&1 | tee -a "$BUILD_LOG"
    rm -f *.iso *.iso.* 2>/dev/null || true

    # Clear old config to ensure fresh generation
    rm -rf config/package-lists
    rm -rf config/includes.chroot
    rm -rf config/hooks
}

# --- CONFIGURE ---
configure_system() {
    log_info "Configuring Live-Build for Debian $DEBIAN_RELEASE..."

    lb config \
        --distribution "$DEBIAN_RELEASE" \
        --architecture "$ARCH" \
        --archive-areas "main contrib non-free non-free-firmware" \
        --security true \
        --updates true \
        --backports false \
        --bootappend-live "boot=live components quiet splash hostname=furryos persistence username=anthro" \
        --linux-packages "linux-image linux-headers" \
        --iso-volume "${OS_NAME}_${VERSION}" \
        --iso-application "$OS_NAME" \
        --iso-publisher "Anthro Entertainment LLC" \
        --memtest none \
        --checksums sha256 \
        2>&1 | tee -a "$BUILD_LOG"

    # FIX: Correct way to handle xattrs in newer squashfs-tools
    echo 'LB_MKSQUASHFS_OPTIONS="-no-xattrs"' >> config/binary
}

# --- DEFINE PACKAGES ---
create_package_lists() {
    log_info "Defining packages (No Bloat)..."
    mkdir -p config/package-lists

    cat << 'EOF' > config/package-lists/furryos-base.list.chroot
# --- DESKTOP CORE ---
mate-desktop-environment-core
mate-utils
mate-control-center
lightdm
network-manager-gnome
plymouth
plymouth-themes

# --- ESSENTIAL TOOLS ---
firefox-esr
curl
wget
git
vim
nano
gparted
htop
neofetch
software-properties-common

# --- AUDIO & MEDIA ---
pipewire
wireplumber
pavucontrol
mpg123                  # Required for Startup Sound (mp3)
ffmpeg

# --- DEPENDENCIES FOR CUSTOM TOOLS ---
python3
python3-gi
python3-cairo
gir1.2-gtk-3.0
libglib2.0-bin
EOF
}

# --- ASSET INJECTION & SCRIPT GENERATION ---
inject_assets() {
    log_info "Injecting assets and generating scripts..."

    local chroot="config/includes.chroot"
    mkdir -p "${chroot}/usr/share/backgrounds/furryos"
    mkdir -p "${chroot}/usr/share/sounds/furryos"
    mkdir -p "${chroot}/usr/local/bin"
    mkdir -p "${chroot}/etc/skel/Desktop"
    mkdir -p "${chroot}/etc/xdg/autostart"
    mkdir -p "${chroot}/usr/share/applications"

    # 1. COPY FILES
    if [ -d "assets/wallpapers" ]; then
        rsync -a assets/wallpapers/ "${chroot}/usr/share/backgrounds/furryos/"
    fi
    if [ -d "assets/sounds" ]; then
        rsync -a assets/sounds/ "${chroot}/usr/share/sounds/furryos/"
    fi
    # Copy generic images
    if [ -d "assets/images" ]; then
        mkdir -p "${chroot}/etc/skel/Pictures"
        rsync -a assets/images/ "${chroot}/etc/skel/Pictures/"
    fi

    # 2. CREATE STARTUP SOUND SCRIPT
    # This plays /usr/share/sounds/furryos/startup.mp3 on login
    cat << 'EOF' > "${chroot}/etc/xdg/autostart/furryos-startup-sound.desktop"
[Desktop Entry]
Type=Application
Name=FurryOS Startup Sound
Exec=mpg123 /usr/share/sounds/furryos/startup.mp3
Terminal=false
NoDisplay=true
X-GNOME-Autostart-enabled=true
EOF

    # 3. CREATE LIVE BORDER SCRIPT (The Orange Pulse)
    cat << 'EOF' > "${chroot}/usr/local/bin/furryos-live-border"
#!/usr/bin/env python3
import gi, cairo, os
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GLib

class LiveBorder(Gtk.Window):
    def __init__(self):
        super().__init__()
        # Only run in live mode check
        if not os.path.exists("/lib/live/mount"): exit(0)

        self.set_title("FurryOS Live")
        self.set_decorated(False)
        self.set_keep_above(True)
        self.set_app_paintable(True)
        self.set_accept_focus(False)
        self.set_skip_taskbar_hint(True)

        screen = self.get_screen()
        visual = screen.get_rgba_visual()
        if visual and screen.is_composited(): self.set_visual(visual)

        monitor = Gdk.Display.get_default().get_primary_monitor()
        geo = monitor.get_geometry()
        self.set_default_size(geo.width, geo.height)
        self.move(0, 0)

        self.alpha = 1.0
        self.fade = -0.05
        self.connect("draw", self.on_draw)
        GLib.timeout_add(100, self.animate)
        self.show_all()

    def animate(self):
        self.alpha += self.fade
        if self.alpha <= 0.4: self.fade = 0.05
        elif self.alpha >= 0.9: self.fade = -0.05
        self.queue_draw()
        return True

    def on_draw(self, widget, cr):
        w, h = widget.get_allocated_width(), widget.get_allocated_height()
        cr.set_source_rgba(1.0, 0.42, 0.21, self.alpha) # #FF6B35
        cr.set_line_width(8)
        cr.rectangle(0, 0, w, h)
        cr.stroke()

        text = "🐾 LIVE MODE 🐾"
        cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
        cr.set_font_size(16)
        ext = cr.text_extents(text)
        cr.set_source_rgba(0,0,0,0.8)
        cr.rectangle((w/2)-(ext.width/2)-10, 0, ext.width+20, ext.height+20)
        cr.fill()
        cr.set_source_rgba(1,1,1,1)
        cr.move_to((w/2)-(ext.width/2), ext.height+5)
        cr.show_text(text)

if __name__ == "__main__":
    app = LiveBorder()
    Gtk.main()
EOF
    chmod +x "${chroot}/usr/local/bin/furryos-live-border"

    # Auto-start the border
    cat << 'EOF' > "${chroot}/etc/xdg/autostart/furryos-live-border.desktop"
[Desktop Entry]
Type=Application
Name=FurryOS Live Border
Exec=/usr/local/bin/furryos-live-border
Terminal=false
NoDisplay=true
X-GNOME-Autostart-enabled=true
EOF

    # 4. CREATE MODE INSTALLER (The "App Store" for Modes)
    cat << 'EOF' > "${chroot}/usr/local/bin/furryos-mode-installer"
#!/usr/bin/env python3
import gi, os, subprocess
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class ModeInstaller(Gtk.Window):
    def __init__(self):
        super().__init__(title="FurryOS Mode Installer")
        self.set_border_width(15)
        self.set_default_size(450, 400)
        self.set_position(Gtk.WindowPosition.CENTER)

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        self.add(vbox)

        lbl = Gtk.Label()
        lbl.set_markup("<span size='x-large' weight='bold'>Choose Your Path</span>")
        vbox.pack_start(lbl, False, False, 10)

        modes = [
            ("👵 Granny Mode", "Installs simple games (Solitaire, Mines) and accessibility tools.", "gnome-games aisleriot gnome-accessibility-themes"),
            ("🎮 Gamer Mode", "Installs Steam, Lutris, GameMode, and Mangohud.", "steam-installer lutris gamemode mangohud"),
            ("💻 Hacker Mode", "Installs VSCode (via repo), Docker, Git, Build-Essential.", "git build-essential docker.io code"),
            ("👻 Paranoid Mode", "Installs Tor, OnionShare, and enables strict Firewall.", "tor onionshare ufw")
        ]

        for name, desc, pkgs in modes:
            btn = Gtk.Button()
            b_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
            l_n = Gtk.Label(); l_n.set_markup(f"<b>{name}</b>")
            l_d = Gtk.Label(label=desc); l_d.set_line_wrap(True)
            b_box.pack_start(l_n, True, True, 0)
            b_box.pack_start(l_d, True, True, 0)
            btn.add(b_box)
            btn.connect("clicked", self.install, name, pkgs)
            vbox.pack_start(btn, True, True, 5)

    def install(self, widget, mode_name, packages):
        confirm = Gtk.MessageDialog(self, 0, Gtk.MessageType.QUESTION, Gtk.ButtonsType.YES_NO, f"Install {mode_name}?")
        confirm.format_secondary_text("This will download and install packages. Internet required.")
        response = confirm.run()
        confirm.destroy()

        if response == Gtk.ResponseType.YES:
            # Open terminal to run the install command
            cmd = f"bash -c 'sudo apt update; sudo apt install -y {packages}; echo Done! Press Enter to close.; read'"
            subprocess.Popen(["mate-terminal", "-e", cmd])

win = ModeInstaller()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
EOF
    chmod +x "${chroot}/usr/local/bin/furryos-mode-installer"

    # Create Desktop Shortcut for Mode Installer
    cat << 'EOF' > "${chroot}/usr/share/applications/furryos-mode-installer.desktop"
[Desktop Entry]
Version=1.0
Type=Application
Name=Install Modes (Gamer/Hacker)
Comment=Customize your FurryOS experience
Exec=/usr/local/bin/furryos-mode-installer
Icon=system-software-install
Terminal=false
Categories=System;
EOF

    # Put it on the user's desktop
    cp "${chroot}/usr/share/applications/furryos-mode-installer.desktop" "${chroot}/etc/skel/Desktop/"
    chmod +x "${chroot}/etc/skel/Desktop/furryos-mode-installer.desktop"
}

# --- BUILD ---
build_iso() {
    log_info "Starting Build..."
    if lb build 2>&1 | tee -a "$BUILD_LOG"; then
        log_success "Build Successful!"
    else
        log_error "Build Failed! Check log."
        exit 1
    fi
}

finalize() {
    local iso_name="${OS_NAME}-${VERSION}-${ARCH}.iso"
    mkdir -p "$BUILD_OUTPUT_DIR"

    if [ -f "live-image-${ARCH}.hybrid.iso" ]; then
        mv "live-image-${ARCH}.hybrid.iso" "$BUILD_OUTPUT_DIR/$iso_name"
        log_success "ISO moved to: $BUILD_OUTPUT_DIR/$iso_name"
    fi

    # Cleanup artifacts
    mv chroot binary cache .build "$PARENT_DIR/" 2>/dev/null || true
}

# --- MAIN ---
check_root
check_dependencies
cleanup_environment
configure_system
create_package_lists
inject_assets
build_iso
finalize
